package com.lt.flashcard.bind;

import org.apache.commons.lang3.StringUtils;
import org.zkoss.bind.ValidationContext;
import org.zkoss.bind.validator.AbstractValidator;
import org.zkoss.zk.ui.Component;
import org.zkoss.zul.Constraint;
import org.zkoss.zul.SimpleConstraint;
import org.zkoss.zul.impl.InputElement;

public class ConstraintValidator extends AbstractValidator {
    @Override
    public void validate(ValidationContext ctx) {
        String arg = (String) ctx.getBindContext().getValidatorArg("constraint");
        if (StringUtils.isNotBlank(arg)) {
            Component com = ctx.getBindContext().getComponent();
            if (com instanceof InputElement) {
                InputElement el = (InputElement) com;
                Constraint cons = (Constraint) el.getAttribute("customconstrain");
                if (cons == null) {
                    cons = arg.indexOf("equals ") >= 0 ? new EqualConstraint(arg.replace("equals ", "")) : new SimpleConstraint(arg);
                    el.setAttribute("customconstrain", cons);
                }
                try {
                    if (cons instanceof EqualConstraint) {
                        String targetName = ((EqualConstraint) cons).getTargetName();
                        Component target = com.getFellow(targetName);
                        if (target != null && target instanceof InputElement) {
                            cons.validate(el, ((InputElement) target).getRawValue());
                        }
                    } else {
                        cons.validate(el, el.getRawValue());
                    }
                } catch (Exception e) {
                    addInvalidMessage(ctx, e.getMessage());
                }
            }
        }
    }
}